// Fill out your copyright notice in the Description page of Project Settings.


#include "BuildActor/WallActor.h"

// Sets default values
AWallActor::AWallActor():MeshScale(FVector(4.0f, 4.0f, 4.0f)), LoopDirection(ELoopDirection::X)
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

    RootSceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootSceneComponent"));
    RootComponent = RootSceneComponent;

}

// Called when the game starts or when spawned
void AWallActor::BeginPlay()
{
	Super::BeginPlay();
   
}

void AWallActor::OnConstruction(const FTransform& Transform)
{
    Super::OnConstruction(Transform);
    CreateWallLoop();
}

// Called every frame
void AWallActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

void AWallActor::CreateWallLoop()
{
    for (UStaticMeshComponent* Component : WallComponents)
    {
        if (Component)
        {
            Component->DestroyComponent();
        }
    }
    WallComponents.Empty();
    
    if (WallMesh == nullptr)
    {
        UE_LOG(LogTemp, Warning, TEXT("WallMesh is not set"));
        return;
    }

    UWorld* World = GetWorld();
    if (World)
    {
        for (int32 i = 0; i < NumberOfWalls; ++i)
        {
            CreateWallSegment(i);

            
        }
    }
}

void AWallActor::CreateWallSegment(int32 Index)
{
    UStaticMeshComponent* WallComponent = NewObject<UStaticMeshComponent>(this);
    if (WallComponent)
    {
        WallComponent->SetStaticMesh(WallMesh);
        WallComponent->SetWorldScale3D(MeshScale);
        WallComponent->RegisterComponent();
        WallComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);

        FVector WallLocation = GetActorLocation();
        FRotator Rotation = GetActorRotation();

        switch (LoopDirection)
        {
        case ELoopDirection::X:
            WallLocation += FVector(Index * DistanceBetweenWalls, 0.0f, 0.0f);
            break;
        case ELoopDirection::Y:
            WallLocation += FVector(0.0f, Index * DistanceBetweenWalls, 0.0f);
            break;
        case ELoopDirection::NegX:
            WallLocation += FVector(-Index * DistanceBetweenWalls, 0.0f, 0.0f);
            break;
        case ELoopDirection::NegY:
            WallLocation += FVector(0.0f, -Index * DistanceBetweenWalls, 0.0f);
            break;
        }

        WallComponent->SetWorldLocationAndRotation(WallLocation, Rotation);
        WallComponents.Add(WallComponent);
    }
}

